import 'dart:async';

import 'package:flutter_app/common/apis/news.dart';
import 'package:flutter_app/common/dto/dto.dart';
import 'package:flutter_app/common/utils/utils.dart';
import 'package:flutter_app/common/values/values.dart';
import 'package:get/get.dart';

import 'state.dart';

class MainLogic extends GetxController {
  MainLogic();

  final state = MainState();

  @override
  Future<void> onInit() async {
    super.onInit();
    state.categories.value = await NewsAPI.categories(
      cacheDisk: false,
    );
    state.newsRecommend.value = await NewsAPI.newsRecommend(
      cacheDisk: false,
    );
    state.channels.value = await NewsAPI.channels(
      cacheDisk: false,
    );
    state.newsPageList.value = await NewsAPI.newsPageList();


    if (CACHE_ENABLE == true) {
      var cacheData = StorageUtil().getJSON(STORAGE_INDEX_NEWS_CACHE_KEY);
      if (cacheData != null) {
        Timer(Duration(seconds: 3), () {
          state.easyRefreshController.callRefresh();
        });
      }
    }

  }


  // 拉取推荐、新闻
  loadNewsData(categoryCode, { bool refresh = false,}) async {
    state.selCategoryCode.value = categoryCode;
    state.newsRecommend.value = await NewsAPI.newsRecommend(
      params: NewsRecommendRequest(categoryCode: categoryCode),
      refresh: refresh,
      cacheDisk: true,
    );
    state.newsPageList.value = await NewsAPI.newsPageList(
      params: NewsPageListRequest(categoryCode: categoryCode),
      refresh: refresh,
      cacheDisk: true,
    );
  }


  Future<void> onRefresh () async {
    await this.loadNewsData(state.selCategoryCode.value, refresh: true,);
    state.easyRefreshController.finishRefresh();
  }
}
